<template>
  <div class="app">
    <div class="login">
      <h1 class="login-title">系统登录</h1>
      <!-- 修复表单 -->
      <div class="input-box">
        <i class="icon icon-user"></i>
        <input type="text" v-model="formData.account" placeholder="请输入账号" />
      </div>
      <div class="input-box">
        <i class="icon icon-lock"></i>
        <input type="password" v-model="formData.password" placeholder="请输入密码" />
      </div>
      <button class="login-btn" @click="login">登录</button>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { checkLogin } from '@/api/account.js';
import { useRouter } from 'vue-router';

const router = useRouter();
const formData = reactive({
  account: '',
  password: ''
});
const errorMessage = ref(''); // 用于存储错误信息

const login = async () => {
  try {
    const res = await checkLogin(formData);
    if (res.code === 0) {
      console.log(res);
      sessionStorage.setItem('userInfo', JSON.stringify({ id: res.id, role: res.role, token: res.token }));
      router.push('/layout');
    } else {
      errorMessage.value = res.message || '登录失败，请检查您的账号和密码';
    }
  } catch (error) {
    errorMessage.value = '登录失败，请稍后再试';
    console.error('登录错误:', error);
  }
};
</script>

<style scoped>
.app {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #2c3e50;
  color: #ecf0f1;
}

.login-title {
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: bold;
  color: white;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
}

.input-box {
  position: relative;
  margin-bottom: 15px;
  width: 300px;
  display: flex;
  align-items: center;
  border: 1px solid #34495e;
  border-radius: 4px;
}

.icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-box input {
  width: 100%;
  padding: 10px 15px 10px 45px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  color: #ecf0f1;
  background-color: #34495e;
  font-family: Arial, Helvetica, sans-serif;
}

input::placeholder {
  color: #999;
}

.login-btn {
  width: 300px;
  padding: 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #ecf0f1;
  background-color: #3498db;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-btn:hover {
  background-color: #2980b9;
}

.error-message {
  margin-top: 10px;
  color: red;
  font-size: 14px;
}
</style>
